package com.imooc.uaa.security.filter;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 改造UsernamePasswordAuthenticationFilter的attemptAuthentication方法
 * 既能用json传参登录,也能用key-value传参登录
 *
 * @author 江黎
 * @date 2022-02-12
 */
public class MyUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        // 登录请求必须是POST
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }

        // 判断请求体的编码方式
        if (request.getContentType().contains(MediaType.APPLICATION_JSON_VALUE)) {
            JsonNode jsonNode;
            try {
                jsonNode = new ObjectMapper().readTree(request.getInputStream());
            } catch (IOException ex) {
                throw new BadCredentialsException("请输入用户名和密码");
            }
            String username = StringUtils.isEmpty(jsonNode.get(getUsernameParameter()).textValue()) ? "" : jsonNode.get(getUsernameParameter()).textValue();
            String password = StringUtils.isEmpty(jsonNode.get(getPasswordParameter()).textValue()) ? "" : jsonNode.get(getPasswordParameter()).textValue();

            username = username.trim();
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
            setDetails(request, authRequest);
            return this.getAuthenticationManager().authenticate(authRequest);
        } else {
            // 不是json方式则由父类方法处理
            return super.attemptAuthentication(request, response);
        }
    }
}
